	<?php
require_once(classdir.'common.php');
require_once(classdir.'db.php');
require_once(classdir.'company.php');
require_once(classdir.'group.php');
require_once(classdir.'groups.php');
require_once(classdir.'role.php');

class user extends common {
	var	$tbl = "users",
			$tblRoles = "roles",
			$tblUserGroup  = "user_group";
	var	$f = array(),
			$role = array(),
			$active_group = array(),
			$company;
	
	
	function __construct($param=NULL,$additional=array()) {
		parent::__construct();
		global $db;
		if (is_null($param)) :
			return true;
		else :
			if (is_array($param)) :
				$this->f = &$param;
				$this->get_role();
			else :
				$where = "";
				if (is_string($param)) :
					$param = block($param);
					$where = " WHERE login='$param'";
				elseif (is_int($param)) :
					$where = " WHERE id='$param'";
				endif;
				
				if (isset($additional['group_id'])){
					$group_id = (int)$additional['group_id'];
					$type = empty($additional['type']) ? 's' : block(substr($additional['type'],0,1));
					$fields = ",ug.group_id, ug.type, ug.uptime, ug.percent, ug.mark";
					$join = "INNER JOIN $this->tblUserGroup as ug ON ug.user_id=u.id AND ug.group_id=$group_id AND ug.type='$type'";
				}			
				$sql = "
					SELECT			
						id,	login,	name,	surname,	address,	city,	state,
						cp,	phone,	mail,	sex,		birthday,	dni,	nss,
						invalid,	study_level,		functional_area, 	professional_category,
						price_group,		company_id,	role_id,
						UNIX_TIMESTAMP(last_login) last_login,
						UNIX_TIMESTAMP() cur_time,hash
						$fields
					FROM
						$this->tbl as u
						$join
					$where
					LIMIT 0,1
				";
				$this->f = $db->query_line($sql);
				if (empty($this->f)) :
					$this->event('login_no_user');
				endif;
				$this->get_role();
			endif;
		endif;
		if (!empty($this->f['company_id'])) :
			$this->company = new company((int) $this->company_id);
		endif;
	}
	
	
	function log_in($login,$pass,$hash="") {
		global $db;
		$return = false;
		$login = block(substr($login,0,200));
		$join = $fields = '';
		if (!empty($pass)) {
			$update = false;
			$pass = md5($pass);
			$where = "password='$pass'";
		} else {
			$update = true;
			$hash = block($hash);
			$where = "hash='$hash'";
		}
		$sql = "
			SELECT
				id,	login,	name,	surname,	address,	city,	state,
				cp,	phone, 	mail,	sex,		birthday,	dni,	nss,
				invalid,	study_level,		functional_area,	professional_category,
				price_group,	company_id,	role_id,
				UNIX_TIMESTAMP(last_login) last_login,
				UNIX_TIMESTAMP() cur_time, hash
				$fields
			FROM
				$this->tbl as u
				$join
			WHERE
				login='$login'
				AND
    			$where
			LIMIT 0,1";
			
		$this->f = $db->query_line($sql);
		if (empty($this->f)) {
			$this->event('login_no_user');
		} else {
			$update_array = array();

			if (!$update){
				$this->hash = md5(date("Ymd his").$this->id.$login.$pass);
				$update_array['hash'] = $this->hash;
			}
			$update_array['last_login'] = array('NOW()');
			$updated = $db->update($this->tbl, $update_array, $this->id);
			
			if (!$updated) {
				$this->event('login_error');
			} else {
				if (!$update){
					$_SESSION['login'] = $this->login;
					$_SESSION['hash'] = $this->hash;
					unset($_SESSION['group_id']);
//					echo "<hr>USER->LOG_IN<hr>";
				}
				$this->event('login_ok');
				$return = true;
			}
			$this->get_role();
		}
		return $return;
	}
	
	
	
	function logged_in() {
		return ($this->id && ($_SESSION['login'] == $this->login) && ($_SESSION['hash'] == $this->hash));
	}

	function login_update(){
		$return = false;
		$login = $_SESSION['login'];
		$hash = $_SESSION['hash'];
		if (empty($login) || empty($_SESSION['hash'])){
			$return = false;
		}else{
			$return = $this->log_in($login,"",$hash);
			if ($return && !empty($_SESSION['group_id'])){
				$this->set_active_group((int)$_SESSION['group_id']);
			}
		}
		return $return;
	}
	
	function logout(){
		global $db;
		if ($this->login_update()){
			$this->hash =  "out";
//			if (!$db->update($this->tbl,$this->f,$this->id())) :
			if (!$this->update()) :
				$this->event('logout_error');
			else :
				$this->f = array();
				$this->role = array();
				$this->company = array();
				$this->active_group = array();
				$this->event('logout_ok');
			endif;
		}else{
			$this->event('logout_ok_already');			
		}
		unset($_SESSION['uid']);
		unset($_SESSION['hash']);
		unset($_SESSION['type']);
		unset($_SESSION['group_id']);
//		echo "<hr>USER->LOGOUT<hr>";
	}
	
	function set_active_group($group_id,$type='auto'){
		global $db;
		if (in_array($type,array('a','admin','ignore'))){
			$this->active_group = new group($this->group_id);
		}else{
			if ($type=='auto'){
				$type = $this->is_student() ? 's' : ($this->is_tutor() ? 't' : 'g');
			}
			$this->active_group = new group((int)$_SESSION['group_id']);
			$sql = "
				SELECT
					user_id,group_id,type,percent,mark,uptime
				FROM
					$this->tblUserGroup
				WHERE
					user_id = {$this->id()}
					AND
					group_id = ".(int)$group_id."
					AND 
					type = '".block($type)."'
				LIMIT 1
			";
			$user_group = $db->query_line($sql);
			if (!empty($user_group)){
				$this->f['group_id']		= (int)$user_group['group_id'];
				$this->f['type']			= $user_group['type'];
				$this->f['percent']		= $user_group['percent'];
				$this->f['mark']			= $user_group['mark'];
				$this->f['uptime']		= $user_group['uptime'];
				$this->active_group = new group($this->group_id);
			}else{
//				unset($_SESSION['group_id']);
//				echo "<hr>USER->SET_ACTIVE_GROUP<hr>";
			}
		}
	}
	
	function create_body() {
		$return = &$this->f;
		if (empty($this->f['login'])){
			$return = false;
			$this->event('create_user_no_login');
		}
		if (empty($this->f['password'])){
			$return = false;
			$this->event('create_user_no_password');
		}else{
			$this->f['password'] = md5($this->f['password']);
		}
		return $return;
	}
	
	function update_body($no_update_fields=array()) {
		global $db;
		$no_update_fields["cur_time"]	= NO_UPDATE;
		$no_update_fields["group_id"]	= NO_UPDATE;
		$no_update_fields["percent"]	= NO_UPDATE;
		$no_update_fields["mark"]		= NO_UPDATE;
		$no_update_fields["uptime"]	= NO_UPDATE;
		$no_update_fields["type"]		= NO_UPDATE;

		if (empty($this->f["password"])) :
			$no_update_fields["password"] = NO_UPDATE;
		else :
			$this->f["password"] = md5($this->f["password"]);
		endif;
//		if (empty($this->f["login"])) :
			$no_update_fields["login"] = NO_UPDATE;
//		endif;
		$this->get_role();
		$uptime_dif = (int)($this->cur_time() - $this->last_login());
		if ($this->logged_id() && $this->is_student() && $this->group->id() && $uptime_dif>0 && $uptime_dif<3600){
			$update_array = array('uptime'=>array("uptime + ".$uptime_dif));
			$db->update($db->tblUserGroup,$update_array,false,'user_id='.$this->id().' AND group_id='.$this->group->id().' AND type="'.$this->type().'"');
		}
		return array_diff_key($this->f,$no_update_fields);
	}
	
	function delete_body() {
		return true;
	}
	
	function get_sent_messages($limit) {
		$this->get_messages(array('user_from_id'=>$this->id()), $limit);
	}
	
	function get_recieved_messages($limit) {
		$this->get_messages(array('user_to_id'=>$this->id()), $limit);
	}
	
	function get_unread_messages($limit) {
		$this->get_messages(array('user_to_id'=>$this->id(),'read'=>false), $limit);
	}
	
	function get_messages($conditions=array(),$limit) {
		$messages = new messages();
		if ($messages->get_items($conditions,$limit)) :
			return $messages->items;
		else :
			return false;
		endif;
	}

	
	function get_role($force=false){
		//dump($this);
		if (!is_object($this->role) || $force){
			$this->role = new role((int)$this->role_id());
		}
	}
	
	function is_admin(){
		$this->get_role();
		return $this->role->slug()=='administrator';
	}
	function is_tutor(){
		$this->get_role();
		return $this->role->slug()=='tutor';
	}
	function is_student(){
		$this->get_role();
		return $this->role->slug()=='student';
	}

	function get_my_groups($type=false){
		$select_array = array('user_id'=>$this->id());
		if ($type){
			$select_array['type'] = $type;
		}else{
			if ($this->is_student()){
				$select_array['type'] = 's';
			}elseif ($this->is_tutor()){
				$select_array['type'] = 't';
			}
		}
		$groups = new groups();
		$groups->get_items($select_array,0);
		return $groups;
	}
	
	function update_percent(){
		if (!empty($this->active_group)){
			global $db;
			$this->active_group->get_lessons();
			$total_count = count($this->active_group->lessons);
			
			$sql = "
				SELECT
					SUM(result) result_sum,
					COUNT(*) cnt,
					SUM(IF((result/100)>=".MARK_MIN.",1,0)) cnt_good
				FROM
					{$db->tblTestResult} as tr
				WHERE
					group_id = {$this->active_group->id()}
					AND
					user_id = {$this->id()}
				GROUP BY 
					group_id,user_id
			";
			$res = $db->query_line($sql);
//			dump($res);
			$this->percent	= $total_count==0	? 0 : round((float)$res['cnt_good']/$total_count*100);
			$this->mark		= ($res['cnt']==0)	? 0 : round((float)$res['result_sum']/(float)$res['cnt'])/100;
			$update_array = array(
									'percent' => $this->percent,
									'mark' => $this->mark,
								);
			$db->update($this->tblUserGroup,$update_array,false,"user_id={$this->id()} AND group_id={$this->active_group->id()} AND type='s'",false);
		}
	}
	
	function the_complete_percent(){
		$return = $this->percent();
		echo $return;
		return $return;
	}

	function can($action){
		$return = false;
		if (!empty($this->role) && $this->role->get_actions()){
			$return = $this->role->has_action($action);
		}
		return $return;
	}
	
	function url($group_id=0,$echo=true){
		$return = url."user/".urlencode($this->login())."/".($group_id ? "$group_id/" : "" );
		if ($echo){
			echo $return;
		}
		return $return;
	}
}
?>
